package com.xzz.mybatis.generator.service;

import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.xzz.mybatis.generator.config.DataSourceConfigBuilder;
import com.xzz.mybatis.generator.config.MyDataSourceConfig;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;


/**
 * @author: hhz
 * @createDate: 2021-3-10
 */
@Service
public class DataSourceChooseService {

    @Resource
    private MyDataSourceConfig myDataSourceConfig;
    /**
     * 选择DBSourceConfig
     * @return DataSourceConfig
     */
    public DataSourceConfig chooseDataSource(String datasourceCode){
        DataSourceConfigBuilder dataSourceConfigBuilder = this.analysisMap2DataSource(datasourceCode);
        if (null != dataSourceConfigBuilder ) {
            DataSourceConfig dataSourceConfig = new DataSourceConfig();
            dataSourceConfig.setPassword(dataSourceConfigBuilder.getPassword());
            dataSourceConfig.setDriverName(dataSourceConfigBuilder.getDriverClassName());
            dataSourceConfig.setUrl(dataSourceConfigBuilder.getUrl());
            dataSourceConfig.setUsername(dataSourceConfigBuilder.getUsername());
            return dataSourceConfig;
        }
        return null;
    }

    /**
     * 获取 DataSourceConfigBuilder
     * @return DataSourceConfigBuilder
     */
    private DataSourceConfigBuilder analysisMap2DataSource(String code){

        Map<String, Map<String,String>> dataSourceMap = myDataSourceConfig.getDatasource();

        String driverClassName = dataSourceMap.get(code).get("driverClassName") ;
        String url = dataSourceMap.get(code).get("url");

        String password = dataSourceMap.get(code).get("password") ;
        String username = dataSourceMap.get(code).get("username") ;
        return DataSourceConfigBuilder
                .builder()
                .driverClassName(driverClassName)
                .username(username)
                .url(url)
                .password(password)
                .build();
    }
}
